package com.gitee.wsl.ext.array


/**
 * Applies PKCS#7 padding to a byte array.
 *
 * PKCS#7 padding ensures that the byte array's length is a multiple of the specified block size.
 * The padding value is the number of bytes added.
 *
 * @param bytes The byte array to pad.
 * @param blockSize The block size to pad the array to.
 * @return A new byte array with PKCS#7 padding applied.
 * @throws IllegalArgumentException if the block size is invalid.
 */
fun pkcs7Pad(bytes: ByteArray, blockSize: Int): ByteArray {
    require(blockSize in 1..255) { "Invalid block size" }
    val paddingLength = blockSize - (bytes.size % blockSize)
    return bytes + ByteArray(paddingLength) { paddingLength.toByte() }
}

/**
 * Removes PKCS#7 padding from a byte array.
 *
 * @param bytes The padded byte array to unpad.
 * @return A new byte array with PKCS#7 padding removed.
 * @throws IllegalArgumentException if the padding is invalid.
 */
fun pkcs7Unpad(bytes: ByteArray): ByteArray {
    require(bytes.isNotEmpty()) { "Input is empty" }
    val paddingLength = bytes.last().toInt() and 0xFF
    require(paddingLength in 1..bytes.size && bytes.takeLast(paddingLength).all { it == paddingLength.toByte() }) {
        "Invalid PKCS#7 padding"
    }
    return bytes.dropLast(paddingLength).toByteArray()
}